package com.chuiyuan.dao;

import com.chuiyuan.entity.Poem;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.sql.SQLException;
import java.util.List;

/**
 * Created by chuiyuan on 4/1/16.
 */
public class PoemDaoImplMyBatis  implements PoemDao {
    private SqlSessionFactory sqlSessionFactory = null ;

    public PoemDaoImplMyBatis(SqlSessionFactory sqlSessionFactory) {
        this.sqlSessionFactory = sqlSessionFactory;
    }


    public void add(Poem poem) throws SQLException {
        int id =-1;
        SqlSession session = sqlSessionFactory.openSession();
        try {
            id = session.insert("Poem.add",poem);
        }finally {
            session.commit();
            session.close();
        }
    }

    public void update(Poem poem) throws SQLException {
        int id =-1;
        SqlSession session = sqlSessionFactory.openSession();
        try {
            id = session.update("update",poem);
        }finally {
            session.commit();
            session.close();
        }
    }

    public void delete(int id) throws SQLException {
        SqlSession session = sqlSessionFactory.openSession();
        try {
            session.delete("delete",id) ;
        }finally {
            session.commit();
            session.close();
        }
    }

    public Poem findById(int id) throws SQLException {
        Poem poem = null ;
        SqlSession  session = sqlSessionFactory.openSession();
        try {
            poem = session.selectOne("findById",id);
        }finally {
            session.close();
        }
        return poem;
    }

    public List<Poem> findAll() throws SQLException{
        List<Poem> list = null ;
        SqlSession session = sqlSessionFactory.openSession();
        try {
            list = session.selectList("findAll");
        }finally {
            session.close();
        }
        return list;
    }
}
